<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
class RoutesController extends AppController {

	var $name = 'Routes';
	var $uses = array('Route', 'Node', 'RouteNodeAssoc', 'PointOfInterest', 'RoutePoiAssoc', 'RouteSchedule', 'Trip', 'TripInfo', 'TelematicUnit');
	
	function index() {
		
		list($order, $limit, $page) = $this->setupPagination();
		$this->set('routes', $this->Route->findAll(NULL, NULL, $order, $limit, $page));
		
	}

	function view($id = null) {
		
		$this->checkRecordExistance($id);
		$this->set('route', $this->Route->read(null, $id));
		$this->set('nodes', $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$id), NULL, 'RouteNodeAssoc.sequence_no ASC'));
		$this->set('pointOfInterests', $this->RoutePoiAssoc->findAll(array('RoutePoiAssoc.route_id'=>$id), NULL, 'RoutePoiAssoc.sequence_no ASC'));
		
	}

	function add() {
		
		if (empty($this->data)) {
			if (!is_array($nodes = $this->Node->generateList())) {
				$nodes = array();
			}
			foreach ($nodes as $nodeId => $nodeCode) {
				$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
				$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
			}
			$nodes[0] = " None";
			asort($nodes);
			$this->set('nodes',          $nodes);
			$this->set('selectedNodes',  $this->getExistingNodes());
			$this->set('availableNodes', $this->getAvailableNodes());
			$this->set('selectedPois',   $this->getExistingPois());
			$this->set('availablePois',  $this->getAvailablePois());
			$this->set('allNodes',       $this->getAllNodes());
			$this->set('allPois',        $this->getAllPois());
			$this->render();
		} else {
			$this->cleanupData();
			$allowCommit = true;
			if (array_key_exists('Node', $this->data) && $this->data['Node']['ids']) {
				if(array_key_exists('PointOfInterest', $this->data) && isset($this->data['PointOfInterest']['ids'])) {
					$poi_ids = explode(";", $this->data['PointOfInterest']['ids']);
				} else {
					$poi_ids = array();
				}
				if (count($poi_ids) == 1 && empty($poi_ids[0])) {
					// No POIs selected
					$poi_ids = array();
				}
				$node_ids      = explode(";", $this->data['Node']['ids']);
				$startNodeId   = $node_ids[0];
				$endNodeId     = $node_ids[count($node_ids)-1];
				$startNodeCode = $this->Node->field('node_code', array('Node.id' => $startNodeId));
				$endNodeCode   = $this->Node->field('node_code', array('Node.id' => $endNodeId));
				$separator     = "-";
				if ($startNodeCode == null || $endNodeCode == null) {
					$flag = false;
				}
				if (array_key_exists('node_id',  $this->data['Route']) && $this->data['Route']['node_id']) {
					$viaNodeCode = $this->Node->field('node_code', array('Node.id' => $this->data['Route']['node_id']));
					$this->data['Route']['route_code'] = $startNodeCode . $separator . $viaNodeCode . $separator . $endNodeCode;  
				} else {
					$this->data['Route']['route_code'] = $startNodeCode . $separator . $endNodeCode;
				}  
				$this->data['Route']['route_code'] = low($this->data['Route']['route_code']);
				$fields['Route.route_code'] = $this->data['Route']['route_code'];
				if (!$this->Route->hasAny($fields)) {
					if (!empty($this->data['Route']['route_segment']) && !(strrchr($this->data['Route']['route_segment'], ',') == ',')) {
						$this->data['Route']['route_segment'] .= ','; 
					}
					$this->Route->begin();
					if ($this->Route->save($this->data)) {
						$this->RouteNodeAssoc->begin();
						$this->RoutePoiAssoc->begin();
						$routeId = $this->Route->getLastInsertID();
						
						// Node section
						$routeNodeAssoc['RouteNodeAssoc']['route_id'] = $routeId;
						foreach ($node_ids as $nodes) {
							$pieces = explode("&", $nodes);
							$routeNodeAssoc['RouteNodeAssoc']['id'] = null;
							$routeNodeAssoc['RouteNodeAssoc']['node_id'] = $pieces[0];
							$routeNodeAssoc['RouteNodeAssoc']['sequence_no'] = $pieces[1];
							unset($fields);
							$fields['Node.id'] = $pieces[0];
							if (!$this->Node->hasAny($fields)) {
								$allowCommit = false;
								break;
							}
							if (!$this->RouteNodeAssoc->save($routeNodeAssoc)) {
								$allowCommit = false;
								break;
							}
						}
						
						// POI section 
						$routePoiAssocs = $this->RoutePoiAssoc->findAll(array('RoutePoiAssoc.route_id'=>$routeId, 'RoutePoiAssoc.id'));
						$flag = true;
						foreach ($routePoiAssocs as $rpa) {
							if (!$this->RoutePoiAssoc->del($rpa['RoutePoiAssoc']['id'])) {
								$allowCommit = false;
								break;
							}
						}
						$routePoiAssoc['RoutePoiAssoc']['route_id'] = $routeId;
						foreach ($poi_ids as $poi) {
							$pieces = explode("&", $poi);
							$routePoiAssoc['RoutePoiAssoc']['id'] = null;
							$routePoiAssoc['RoutePoiAssoc']['point_of_interest_id'] = $pieces[0];
							$routePoiAssoc['RoutePoiAssoc']['sequence_no'] = $pieces[1];
							unset($fields);
							$fields['PointOfInterest.id'] = $pieces[0];
							if (!$this->PointOfInterest->hasAny($fields)) {
								$allowCommit = false;
								break;
							}
							if (!$this->RoutePoiAssoc->save($routePoiAssoc)) {
								$allowCommit = false;
								break;
							}
						}
						
						if ($allowCommit) {
							$this->RouteNodeAssoc->commit();
							$this->RoutePoiAssoc->commit();
							$this->Route->commit();
							$this->Session->setFlash('New Route has been added.', 'message_ok');
							$this->redirect('/routes/index');
						} else {
							$this->RouteNodeAssoc->rollback();
							$this->RoutePoiAssoc->rollback();
							$this->Route->rollback();
							if (!is_array($nodes = $this->Node->generateList())) {
								$nodes = array();
							}
							$nodes[0] = " None";
							asort($nodes);
							$this->set('nodes',          $nodes);
							$this->set('selectedNodes',  $this->getExistingNodes());
							$this->set('availableNodes', $this->getAvailableNodes());
							$this->set('selectedPois',   $this->getExistingPois());
							$this->set('availablePois',  $this->getAvailablePois());
							$this->set('allNodes',       $this->getAllNodes());
							$this->set('allPois',        $this->getAllPois());
							$this->Session->setFlash('Please select some nodes for this route.', 'message_error');
						}
					} else {
						$this->Route->rollback();
						if (!is_array($nodes = $this->Node->generateList())) {
							$nodes = array();
						}
						foreach ($nodes as $nodeId => $nodeCode) {
							$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
							$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
						}
						$nodes[0] = " None";
						foreach ($nodes as $nodeId => $nodeCode) {
							$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
							$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
						}
						asort($nodes);
						$this->set('nodes',          $nodes);
						$this->set('selectedNodes',  $this->getExistingNodes());
						$this->set('availableNodes', $this->getAvailableNodes());
						$this->set('selectedPois',   $this->getExistingPois());
						$this->set('availablePois',  $this->getAvailablePois());
						$this->set('allNodes',       $this->getAllNodes());
						$this->set('allPois',        $this->getAllPois());
					//	$this->set('selectedNodes',   $this->getSelectedNodes($node_ids));
					//	$this->set('availableNodes', $this->getAvailableNodes(null, $node_ids));
					//	$this->set('selectedPois',   $this->getSelectedPois($poi_ids));
					//	$this->set('availablePois',  $this->getAvailablePois(null, $poi_ids));
						$this->Session->setFlash('Please correct errors below.', 'message_error');
					}
				} else {
					$this->Route->rollback();
					if (!is_array($nodes = $this->Node->generateList())) {
						$nodes = array();
					}
					foreach ($nodes as $nodeId => $nodeCode) {
						$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
						$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
					}
					$nodes[0] = " None";
					asort($nodes);
					$this->set('nodes',          $nodes);
					$this->set('selectedNodes',  $this->getExistingNodes());
					$this->set('availableNodes', $this->getAvailableNodes());
					$this->set('selectedPois',   $this->getExistingPois());
					$this->set('availablePois',  $this->getAvailablePois());
					$this->set('allNodes',       $this->getAllNodes());
					$this->set('allPois',        $this->getAllPois());
				//	$this->set('selectedNodes',   $this->getSelectedNodes($node_ids));
				//	$this->set('selectedPois',   $this->getSelectedPois($poi_ids));
				//	$this->set('availableNodes', $this->getAvailableNodes(null, $node_ids));
				//	$this->set('availablePois',  $this->getAvailablePois(null, $poi_ids));
					$this->Session->setFlash('Generated Route code alredy exists.', 'message_error');
				}
			} else {
				$this->Route->invalidFields($this->data); 
				if (!is_array($nodes = $this->Node->generateList())) {
					$nodes = array();
				}
				foreach ($nodes as $nodeId => $nodeCode) {
					$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
					$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
				}
				$nodes[0] = " None";
				asort($nodes);
				$this->set('nodes',          $nodes);
				$this->set('selectedNodes',  $this->getExistingNodes());
				$this->set('availableNodes', $this->getAvailableNodes());
				$this->set('selectedPois',   $this->getExistingPois());
				$this->set('availablePois',  $this->getAvailablePois());
				$this->set('allNodes',       $this->getAllNodes());
				$this->set('allPois',        $this->getAllPois());
				$this->set('selectedNodes',   $this->getSelectedNodes($node_ids));
			//	$this->set('availableNodes', $this->getAvailableNodes(null, $node_ids));
			//	$this->set('availableNodes', $this->getAvailableNodes(null, $node_ids));
			//	$this->set('availablePois',  $this->getAvailablePois(null, $poi_ids));
				$this->Session->setFlash('Please select some nodes for this route.', 'message_error');
			} 
		}
	}

	function edit($id = null, $confirm = null) {
		
		if ($confirm === null){
			$this->confirm_edit($id);
			exit(0);
		} else if ($confirm === 0) {
			$this->Session->setFlash('Operation cancelled by user.', 'message_ok');
			$this->redirect('/routes/index');
			exit(0);
		} else {
			// Delete All route schedule entries which uses this route
			$this->RouteSchedule->recursive = 1;
			if (!is_array($routeSchedules = $this->RouteSchedule->findAll(array('RouteSchedule.route_id' => $id)))) {
				$routeSchedules = array();
			}
			$this->RouteSchedule->begin();
			$this->TripInfo->begin();
			$allowCommit = true;
			foreach ($routeSchedules as $routeSchedule) {
				// Delete route schedule
				$fields['Trip.route_schedule_id'] = $routeSchedule['RouteSchedule']['id']; 
				$fields['Trip.trip_status'] = "S";
				if ($this->Trip->hasAny($fields)){
					// Active trip with this route schedule exists.
					$this->Session->setFlash('A trip with through this route is active. Please end or cancel that trip inorder to edit this route.', 'message_error');
					$this->redirect('/routes/index');
					exit(0);
				}
				if ($this->Trip->findCount(array('Trip.route_schedule_id'=>$routeSchedule['RouteSchedule']['id'])) > 0) {
					if (!$this->pushToTripInfoQueue($routeSchedule['RouteSchedule']['id'])) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating Route schedule info queue, The Route not deleted.', 'message_error');
					}
				}
				if (!$this->RouteSchedule->del($routeSchedule['RouteSchedule']['id'])) {
					$allowCommit = false;
					$this->Session->setFlash('Unable to delete Route schedule.', 'message_ok');
				} else {
					$this->Session->setFlash('The Route schedule(s) deleted.', 'message_ok');
				}
			}
			if ($allowCommit) {
				$this->RouteSchedule->commit();
				$this->TripInfo->commit();
			} else {
				$this->RouteSchedule->rollback();
				$this->TripInfo->rollback();
				$this->redirect('/routes/index');
			}
			
		}
		
		if (empty($this->data)) {
			$this->checkRecordExistance($id);
			$this->data = $this->Route->read(null, $id);
			if (!is_array($nodes = $this->Node->generateList())) {
				$nodes = array();
			}
			foreach ($nodes as $nodeId => $nodeCode) {
				$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
				$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
			}
			$nodes[0] = " None";
			asort($nodes);
			$this->set('nodes',          $nodes);
			$this->set('selectedNodes',  $this->getExistingNodes($id));
			$this->set('availableNodes', $this->getAvailableNodes($id));
			$this->set('selectedPois',   $this->getExistingPois($id));
			$this->set('availablePois',  $this->getAvailablePois($id));
			$this->set('allNodes',       $this->getAllNodes($id));
			$this->set('allPois',        $this->getAllPois($id));
			$this->render('edit');
		} else {
			$this->cleanupData();
			$allowCommit = true;
			if (array_key_exists('Node', $this->data) && isset($this->data['Node']['ids'])) {
				if (array_key_exists('PointOfInterest', $this->data) && isset($this->data['PointOfInterest']['ids'])) {
					$poi_ids = explode(";", $this->data['PointOfInterest']['ids']);
				} else {
					$poi_ids = array();
				}
				if (count($poi_ids) == 1 && empty($poi_ids[0])) {
					// No POIs selected
					$poi_ids = array();
				}
				$node_ids      = explode(";", $this->data['Node']['ids']);
				$startNodeId   = $node_ids[0];
				$endNodeId     = $node_ids[count($node_ids)-1];
				$startNodeCode = $this->Node->field('node_code', array('Node.id' => $startNodeId));
				$endNodeCode   = $this->Node->field('node_code', array('Node.id' => $endNodeId));
				if (!empty($this->data['Route']['route_segment']) && !(strrchr($this->data['Route']['route_segment'], ',') == ',')) {
					$this->data['Route']['route_segment'] .= ','; 
				}
				$separator     = "-";
				if ($startNodeCode == null || $endNodeCode == null) {
					$allowCommit = false;
				}
				if (array_key_exists('node_id',  $this->data['Route']) && $this->data['Route']['node_id']) {
					$viaNodeCode = $this->Node->field('node_code', array('Node.id' => $this->data['Route']['node_id']));
					$this->data['Route']['route_code'] = $startNodeCode . $separator . $viaNodeCode . $separator . $endNodeCode;  
				} else {
					$this->data['Route']['route_code'] = $startNodeCode . $separator . $endNodeCode;
				}  
				$this->data['Route']['route_code'] = low($this->data['Route']['route_code']);
				$fields['Route.route_code'] = $this->data['Route']['route_code'];
				$fields['Route.id'] = '<> '.$id; 
				if (!$this->Route->hasAny($fields)) {
					$this->Route->begin();
					if ($this->Route->save($this->data)) {
						$this->RouteNodeAssoc->begin();
						$this->RoutePoiAssoc->begin();
						
						// nodes section
						$routeNodeAssocs = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$id, 'RouteNodeAssoc.id'));
						foreach ($routeNodeAssocs as $rna) {
							if (!$this->RouteNodeAssoc->del($rna['RouteNodeAssoc']['id'])) {
								$allowCommit = false;
								break;
							}
						}
						$routeNodeAssoc['RouteNodeAssoc']['route_id'] = $id;
						foreach ($node_ids as $node) {
							$pieces = explode("&", $node);
							$routeNodeAssoc['RouteNodeAssoc']['id'] = null;
							$routeNodeAssoc['RouteNodeAssoc']['node_id'] = $pieces[0];
							$routeNodeAssoc['RouteNodeAssoc']['sequence_no'] = $pieces[1];
							unset($fields);
							$fields['Node.id'] = $pieces[0];
							if (!$this->Node->hasAny($fields)) {
								$allowCommit = false;
								$this->Session->setFlash('Selected Node dos not exist.', 'message_error');
								break;
							}
							if (!$this->RouteNodeAssoc->save($routeNodeAssoc)) {
								$allowCommit = false;
								$this->Session->setFlash('Unable to add nodes for the Route.', 'message_error');
								break;
							}
						}
						// pois section
						$routePoiAssocs = $this->RoutePoiAssoc->findAll(array('RoutePoiAssoc.route_id'=>$id, 'RoutePoiAssoc.id'));
						$flag = true;
						foreach ($routePoiAssocs as $rpa) {
							if (!$this->RoutePoiAssoc->del($rpa['RoutePoiAssoc']['id'])) {
								$allowCommit = false;
								break;
							}
						}
						$routePoiAssoc['RoutePoiAssoc']['route_id'] = $id;
						foreach ($poi_ids as $poi) {
							$pieces = explode("&", $poi);
							$routePoiAssoc['RoutePoiAssoc']['id'] = null;
							$routePoiAssoc['RoutePoiAssoc']['point_of_interest_id'] = $pieces[0];
							$routePoiAssoc['RoutePoiAssoc']['sequence_no'] = $pieces[1];
							unset($fields);
							$fields['PointOfInterest.id'] = $pieces[0];
							if ($this->PointOfInterest->hasAny($fields)) {
								if (!$this->RoutePoiAssoc->save($routePoiAssoc)) {
									$allowCommit = false;
									$this->Session->setFlash('Unable to add pois for the Route.', 'message_error');
									break;
								}
							} else {
								/*
								$this->Session->setFlash('Selected POI dos not exist.', 'message_error');
								$allowCommit = false;
								break;
								*/
							}
						}
						
						if ($allowCommit) {
							$this->RouteNodeAssoc->commit();
							$this->RoutePoiAssoc->commit();
							$this->Route->commit();
							$this->Session->setFlash('The Route has been saved.', 'message_ok');
							$this->redirect('/routes/index');
						} else {
							$this->RouteNodeAssoc->rollback();
							$this->RoutePoiAssoc->rollback();
							$this->Route->rollback();
							if (!is_array($nodes = $this->Node->generateList())) {
								$nodes = array();
							}
							foreach ($nodes as $nodeId => $nodeCode) {
								$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
								$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
							}
							$nodes[0] = " None";
							asort($nodes);
							$this->set('nodes',          $nodes);
							$this->set('allNodes',       $this->getAllNodes($id));
							$this->set('selectedNodes',  $this->getExistingNodes($id));
							$this->set('availableNodes', $this->getAvailableNodes($id));
							$this->set('selectedPois',   $this->getExistingPois($id));
							$this->set('availablePois',  $this->getAvailablePois($id));
							$this->set('allNodes',       $this->getAllNodes($id));
							$this->set('allPois',        $this->getAllPois($id));
							//$this->Session->setFlash('Unable to add nodes/pois for the Route.', 'message_error');
						}
					} else {
						$this->Route->rollback();
						if (!is_array($nodes = $this->Node->generateList())) {
							$nodes = array();
						}
						foreach ($nodes as $nodeId => $nodeCode) {
							$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
							$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
						}
						$nodes[0] = " None";
						asort($nodes);
						$this->set('nodes',          $nodes);
						$this->set('selectedNodes',  $this->getExistingNodes($id));
						$this->set('availableNodes', $this->getAvailableNodes($id));
						$this->set('selectedPois',   $this->getExistingPois($id));
						$this->set('availablePois',  $this->getAvailablePois($id));
						$this->set('allNodes',       $this->getAllNodes($id));
						$this->set('allPois',        $this->getAllPois($id));
						$this->Session->setFlash('Please correct errors below.', 'message_error');
					}
				} else {
					$this->Route->rollback();
					if (!is_array($nodes = $this->Node->generateList())) {
						$nodes = array();
					}
					foreach ($nodes as $nodeId => $nodeCode) {
						$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
						$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
					}
					$nodes[0] = " None";
					asort($nodes);
					$this->set('nodes',          $nodes);
					$this->set('selectedNodes',  $this->getExistingNodes($id));
					$this->set('availableNodes', $this->getAvailableNodes($id));
					$this->set('selectedPois',   $this->getExistingPois($id));
					$this->set('availablePois',  $this->getAvailablePois($id));
					$this->set('allNodes',       $this->getAllNodes($id));
					$this->set('allPois',        $this->getAllPois($id));
					$this->Session->setFlash('Generated Route code alredy exists.', 'message_error');
				}
			} else {
				$this->Route->invalidFields($this->data); 
				if (!is_array($nodes = $this->Node->generateList())) {
					$nodes = array();
				}
				$nodes[0] = " None";
				foreach ($nodes as $nodeId => $nodeCode) {
					$nodeName = $this->Node->field('Node.node_name', "Node.id =".$nodeId);
					$nodes[$nodeId] = $nodeName.' ('.$nodeCode.')';
				}
				asort($nodes);
				$this->set('nodes',          $nodes);
				$this->set('selectedNodes',  $this->getExistingNodes($id));
				$this->set('availableNodes', $this->getAvailableNodes($id));
				$this->set('selectedPois',   $this->getExistingPois($id));
				$this->set('availablePois',  $this->getAvailablePois($id));
				$this->set('allNodes',       $this->getAllNodes($id));
				$this->set('allPois',        $this->getAllPois($id));
				$this->Session->setFlash('Please select some nodes for this route.', 'message_error');
			} 
		}
	}

	function delete($id = null, $confirm = null) {
		
		if ($confirm === null){
			$this->confirm_delete($id);
			exit(0);
		} else if ($confirm === 0) {
			$this->Session->setFlash('Operation cancelled by user.', 'message_ok');
			$this->redirect('/routes/index');
			exit(0);
		} else {
			// Delete All route schedule entris which uses this route
			$this->RouteSchedule->recursive = 1;
			if (!is_array($routeSchedules = $this->RouteSchedule->findAll(array('RouteSchedule.route_id' => $id)))) {
				$routeSchedules = array();
			}
			$this->RouteSchedule->begin();
			$this->TripInfo->begin();
			$allowCommit = true;
			foreach ($routeSchedules as $routeSchedule) {
				// Delete route schedule
				$fields['Trip.route_schedule_id'] = $routeSchedule['RouteSchedule']['id']; 
				$fields['Trip.trip_status'] = "S";
				if ($this->Trip->hasAny($fields)){
					// Active trip with this route schedule exists.
					$this->Session->setFlash('A trip with through this route is active. Please end or cancel that trip inorder to delete this route.', 'message_error');
					$this->redirect('/routes/index');
					exit(0);
				}
				if ($this->Trip->findCount(array('Trip.route_schedule_id'=>$routeSchedule['RouteSchedule']['id'])) > 0) {
					if (!$this->pushToTripInfoQueue($routeSchedule['RouteSchedule']['id'])) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating Route schedule info queue, The Route not deleted.', 'message_error');
					}
				}
				if (!$this->RouteSchedule->del($routeSchedule['RouteSchedule']['id'])) {
					$allowCommit = false;
					$this->Session->setFlash('Unable to delete Route schedule.', 'message_error');
				}
			}
			if ($allowCommit) {
				$this->RouteSchedule->commit();
				$this->TripInfo->commit();
				$this->Session->setFlash('The Route schedule(s) deleted.', 'message_ok');
			} else {
				$this->RouteSchedule->rollback();
				$this->TripInfo->rollback();
				$this->redirect('/routes/index');
			}
			
		}
		
		$this->checkRecordExistance($id);
		$fields['RouteSchedule.route_id'] = $id; 
		$fields['Trip.trip_status'] = "S";
		if ($this->Trip->hasAny($fields)) {
			// Active trip through route exists.
			$this->Session->setFlash('A trip through this route is active. Please end or cancel that trip inorder to delete this route.', 'message_error');
			$this->redirect('/routes/view/'.$id);
			exit(0);
		}
		$this->Route->begin();
		if ($this->Route->del($id)) {
			$this->Route->commit();
			$this->Session->setFlash('The Route deleted.', 'message_ok');
			$this->redirect('/routes/index');
		} else {
			$this->Route->rollback();
			$this->showError(ERROR_DELETE, 'Unable to delete record.');
		}
	}
	
	function confirm_edit($id) {
		
		if (empty($this->data)) {
			$this->set('route_id', $id);
			$this->set('route_name', $this->Route->field('Route.route_name', "Route.id =".$id));
			$this->RouteSchedule->recursive = 1;
			if (!is_array($routeSchedules = $this->RouteSchedule->findAll(array('RouteSchedule.route_id' => $id)))) {
				$routeSchedules = array();
			}
			if (count($routeSchedules) == 0) {
				$this->edit($id, 1);
				exit(0);
			}		
			$this->set('routeSchedules', $routeSchedules);
			$this->render('confirm_edit');
			exit(0);
		} else {
			$this->checkJavaScript();
			if($this->data['Route']['confirm']){
				unset($this->data);
				$this->edit($id, 1);
				exit(0);
			} else {
				$this->edit($id, 0);
				exit(0);
			}
		}
		
	}
	
	function confirm_delete($id) {
		
		if (empty($this->data)) {
			$this->set('route_id', $id);
			$this->set('route_name', $this->Route->field('Route.route_name', "Route.id =".$id));
			$this->RouteSchedule->recursive = 1;
			if (!is_array($routeSchedules = $this->RouteSchedule->findAll(array('RouteSchedule.route_id' => $id)))) {
				$routeSchedules = array();
			}
			if (count($routeSchedules) == 0) {
				$this->delete($id, 1);
				exit(0);
			}		
			$this->set('routeSchedules', $routeSchedules);
			$this->render('confirm_delete');
			exit(0);
		} else {
			$this->checkJavaScript();
			if ($this->data['Route']['confirm']) {
				unset($this->data);
				$this->delete($id, 1);
				exit(0);
			} else {
				$this->delete($id, 0);
				exit(0);
			}
		}
		
	}
	
	function view_multiple($id = null) {
		$flag = true;
		if (isset($this->params['url']['ids'])) {
			$ids = explode(";", $this->params['url']['ids']);
			if (count($ids) > 0) {
				foreach ($ids as $id) {
					if ($id != null) {
						$id = intval($id); 
						unset($fields);
						$fields['Route.id'] = $id;
						if ($this->Route->hasAny($fields)) {
							$validIds[] = $id; 
						}
					} 
				}
				if (isset($validIds)) {
					$idList       = implode(",", $validIds);
					$conditions   = array("Route.id IN ($idList)");
					$this->Route->recursive = 4;
					$routes       = $this->Route->findAll($conditions);
				} else {
					$flag = false;
				}
			} else {
				$flag = false;
			}
		} else {
			$flag = false;
		}
		if ($flag) {
			$this->set('routes', $routes);
			
		} else {
			$this->Session->setFlash('No Routes selected to view.', 'message_error');
			$this->redirect('/routes/index');
		}
	}
	
	function getAllNodes() {
		
		$nodes = $this->Node->findAll(NULL, NULL, 'Node.node_name ASC');
		
		return $nodes; 
	}
	
	function getAvailableNodes($routeId = null, $exceptions=null) {
		
		if ($routeId == null) {
			if ($exceptions == null) {
				if (!is_array($nodes = $this->Node->findAll(NULL))) {
					$nodes = array();
				}
			} else {
				$nodeList = "";
				foreach ($exceptions as $nodeId) {
					$nodeList .= $nodeId. ",";
				}
				//Remove the last comma from node List
				$nodeList = substr($nodeList, 0, -1);
				$nodes = $this->Node->findAll(array("Node.id NOT IN ($nodeList)"));
			}
		} else {
			$allNodes  = $this->Node->findAll();
			$nodes = array();
			foreach ($allNodes as $node) {
				$fields['RouteNodeAssoc.route_id'] = $routeId; 
				$fields['RouteNodeAssoc.node_id'] = $node['Node']['id'];
				if (!$this->RouteNodeAssoc->hasAny($fields)) {
					$nodes[] = $node; 
				}
			}
		}
		return  $nodes;
		
	}
	
	function getExistingNodes($routeId = null) {
		
		if ($routeId == null) {
			$nodes = array();
		} else {
		//	$nodes = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId));
			$nodes = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId), NULL, 'RouteNodeAssoc.sequence_no ASC');
		}
		return $nodes; 
	}
	
	function getSelectedNodes($nodeIds) {
		
		if ($nodeIds == null) {
			$nodes = array();
		} else {
			$nodeList = "";
			foreach ($nodeIds as $nodeId) {
				$nodeList .= $nodeId. ",";
			}
			//Remove the last comma from node List
			$nodeList = substr($nodeList, 0, -1);
			$nodes = $this->Node->findAll(array("Node.id IN ($nodeList)"));
		}
		return $nodes; 
	}
	
	function getAllPois() {
		
		$pois = $this->PointOfInterest->findAll(NULL, NULL, 'PointOfInterest.point_of_interest_name ASC');
		
		return $pois; 
	}
	
	function getAvailablePois($routeId = null, $exceptions=null) {
		
		if ($routeId == null) {
			if ($exceptions == null) {
				if (!is_array($pois = $this->PointOfInterest->findAll(NULL))) {
					$pois = array();
				}
			} else {
				$poiList = "";
				foreach ($exceptions as $poiId) {
					$poiList .= $poiId. ",";
				}
				//Remove the last comma from node List
				$poiList = substr($poiList, 0, -1);
				$pois    = $this->PointOfInterest->findAll(array("PointOfInterest.id NOT IN ($poiList)"));
			}
		} else {
			$allPois  = $this->PointOfInterest->findAll();
			$pois = array();
			foreach ($allPois as $poi) {
				$fields['RoutePoiAssoc.route_id'] = $routeId; 
				$fields['RoutePoiAssoc.point_of_interest_id'] = $poi['PointOfInterest']['id'];
				if (!$this->RoutePoiAssoc->hasAny($fields)) {
					$pois[] = $poi; 
				}
			}
		}
		return  $pois;
		
	}
	
	function getExistingPois($routeId = null) {
		
		if ($routeId == null) {
			$pois = array();
		} else {
		//	$pois = $this->RoutePoiAssoc->findAll(array('RoutePoiAssoc.route_id'=>$routeId));
			$pois = $this->RoutePoiAssoc->findAll(array('RoutePoiAssoc.route_id'=>$routeId), NULL, 'RoutePoiAssoc.sequence_no ASC');
		}
		return $pois; 
	}
	
	function getSelectedPois($poiIds) {
		
		if ($poiIds == null) {
			$pois = array();
		} else {
			$poiList = "";
			foreach ($poiIds as $poiId) {
				$poiList .= $poiId. ",";
			}
			//Remove the last comma from node List
			$poiList = substr($poiList, 0, -1);
			$pois = $this->PointOfInterest->findAll(array("PointOfInterest.id IN ($poiList)"));
		}
		return $pois; 
	}
	
	/**
	 * If a Route schedule is deleted, a new trip info id is generated with 'route_schedule_deleted' set 
	 * and all the ivtu(vehicles) codes are collected and stored in 'vehicle_list' field.
	 *
	 * @param unknown_type $routeScheduleId
	 * @return unknown
	 */
	function pushToTripInfoQueue($routeScheduleId) {
		
		//  To get TU List
		$tuList = "";
		$vehicles = $this->Trip->findAll(array('Trip.route_schedule_id'=>$routeScheduleId));
		foreach ($vehicles as $vehicle) {
			$telematicUnits = $this->TelematicUnit->findAll(array('Vehicle.id'=>$vehicle['Vehicle']['id'], 'TelematicUnit.telematic_unit_location_type'=>'v'), 'TelematicUnit.telematic_unit_code');
			foreach ($telematicUnits as $telematicUnit) {
				$tuList .= $telematicUnit['TelematicUnit']['telematic_unit_code']. ",";
			}
		}
		
		// Remove the last comma from the TU List
		$tuList = substr($tuList, 0, -1);
		
		$data['TripInfo']['route_schedule_id'] = $routeScheduleId;
		$data['TripInfo']['route_schedule_deleted'] = 1;
		$data['TripInfo']['vehicle_list'] = $tuList;
		return $this->TripInfo->save($data);
		
	}


}
?>